﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using BlueLotus7.ArchiveSystem.Common;

namespace BlueLotus7.ExternalApi.TencentStatusApi
{
    public static class TencentStatusRetriver
    {
        const string statusUrl = "http://wpa.qq.com/pa?p=1:{0}:1";
        const long onlineLength = 2329;
        const long offlineLength = 2262;


        public static QQStatus RetrieveQQStatusByUid(string uid)
        {
            return RetrieveQQStatusByUid(uid, 0);
        }

        private static QQStatus RetrieveQQStatusByUid(string uid, int currentRetryCount)
        {
            QQStatus result = QQStatus.Unknown;

            if (!string.IsNullOrWhiteSpace(uid))
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format(statusUrl, uid));
                WebResponse response = null;
                try
                {
                    response = request.GetResponse();
                    switch (response.ContentLength)
                    {
                        case onlineLength:
                            result = QQStatus.Online;
                            break;
                        case offlineLength:
                            result = QQStatus.Offline;
                            break;
                    }
                }
                catch (WebException we)
                {
                    request.Abort();
                }
                catch (Exception ex)
                {
                    throw new Exception("Fail to retrieve QQ status by uid.", ex);
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                        response = null;
                    }
                }

                if (result == QQStatus.Unknown && currentRetryCount <= Global.retryCountLimit)
                {
                    currentRetryCount++;
                    result = RetrieveQQStatusByUid(uid, currentRetryCount);
                }
            }

            return result;
        }
    }
}
